﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Tycho.Peyote.Mock {
    /// <summary>
    /// Interaction logic for ListItem.xaml
    /// </summary>
    public partial class ListItem : UserControl {
        public List ContainingList { get; set; }
        private bool Dragging;
        private Point DragStart;
        private ListItemReorderer ListItemReorderer;
        public string Data { get; set; }

        public ListItem (string data, List containingList, ListItemReorderer listItemReorderer) {
            InitializeComponent ();

            ContainingList = containingList;
            ListItemReorderer = listItemReorderer;
            Data = data;
            DataContext = this;
        }

        private void StackPanel_PreviewDrop (object sender, DragEventArgs e) {
            ListItemReorderer.Drop ();
            e.Handled = true;
        }

        private void StackPanel_PreviewDragOver (object sender, DragEventArgs e) {
            ListItemReorderer.DragOver (this, e);
            e.Handled = true;
        }

        private void DeleteButton_Click (object sender, RoutedEventArgs e) {
            ContainingList.Remove (this);
            e.Handled = true;
        }

        void OrderHandle_MouseLeftButtonDown (object sender, MouseButtonEventArgs e) {
            var element = (FrameworkElement) sender;
            if (!element.IsMouseCaptured) {
                Dragging = true;
                DragStart = e.GetPosition (element);
            }
            e.Handled = true;
        }

        void OrderHandle_MouseMove (object sender, MouseEventArgs e) {
            var element = (FrameworkElement) sender;
            if (Dragging) {
                Point currentPos = e.GetPosition (element);

                if ((Math.Abs (currentPos.X - DragStart.X) > SystemParameters.MinimumHorizontalDragDistance)
                    || (Math.Abs (currentPos.Y - DragStart.Y) > SystemParameters.MinimumVerticalDragDistance)) {
                    element.CaptureMouse ();

                    ListItemReorderer.StartReorder (this);
                    DragDropEffects de = DragDrop.DoDragDrop (element, element, DragDropEffects.Move);
                    Dragging = false;
                    element.ReleaseMouseCapture ();
                }
            }
            e.Handled = true;
        }
    }
}
